import {
  queryAliyunOssUploadPresigned,
  queryCtyunOssUploadPresigned,
  queryDictsByDictTypeId,
  queryDictTypes,
  queryUploadFile,
  UPLOAD_FILE_API_PATH
} from '@/services';
import {queryBackendEnums} from '@/services/core/GlobalService';
import {queryCurrentUser} from '@/services/system/user/UserService';
import {getAuthInfo, getAuthToken} from '@/utils/auth';
import {history, RequestConfig} from "@umijs/max";
import {message} from 'antd';
import {BackendEnum, BackendEnumItemKeyValPair, BackendEnumsKeyValPair, BackendEnumsTypeKeyValPair, DEFAULT_LOGIN_PATH as LOGIN_PATH} from "kf-web-library";

import queryString from 'query-string';
import React from 'react';
import {errorConfig} from '@/utils/request';
import {AppInitialState, appInitialStateImpl} from "@/AppInitialState";
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

/**
 * @name  全局初始化数据配置
 * 用于 Layout 用户信息和权限初始化
 * 更多信息见文档：https://next.umijs.org/docs/api/runtime-config#getinitialstate
 */
export async function getInitialState(): Promise<AppInitialState> {
  //获取当前登录用户信息函数
  const fetchUserInfo = async () => {
    try {
      const currentUserResp = await queryCurrentUser({
        skipErrorHandler: true,
      });
      return currentUserResp.data;
    } catch (error) {
      //如果未能获取, 就重定向到登录页面
      //message.error('未登陆或登陆已过时，请重新登陆！');
      //history.push(LOGIN_PATH);
    }
    return undefined;
  };

  //获取后端枚举定义
  //获取后端枚举定义
  const fetchBackendEnums = async () => {
    const backendEnumsResp = await queryBackendEnums();
    const backendEnumArray = backendEnumsResp.data;

    // 将 BackendEnum[] 转换为 BackendEnumsKeyValPair
    const ret: BackendEnumsKeyValPair = {};
    const typeRet: BackendEnumsTypeKeyValPair = {};
    backendEnumArray.forEach((item: BackendEnum) => {
      const opts = item.enums;
      const mappingResult: BackendEnumItemKeyValPair = {};
      opts.forEach((opt) => {
        mappingResult[opt.enumName] = opt;
      });
      ret[item.enumType] = mappingResult;
      typeRet[item.enumType] = item.enumTypeDesc;
    });
    return {
      enumDict: ret,
      enumTypeDict: typeRet
    };
  };

  const backendEnum = await fetchBackendEnums();

  //获取登录后需要fetch的信息 (用户信息, 后端枚举, 展示菜单定义)
  const fetchLoggedInfo = async () => {
    const currentUserInfo = await fetchUserInfo();
    if (!currentUserInfo) {
      return undefined;
    }
    return {
      currentUserInfo,
      currentAuthInfo: getAuthInfo(),
    };
  };

  let loggedInfo: any = undefined;
  // 如果不是登录页面才执行
  if (window.location.pathname !== LOGIN_PATH) {
    loggedInfo = await fetchLoggedInfo();
  } else {
    loggedInfo = {
      currentAuthInfo: getAuthInfo(),
    };
  }


  return {

    queryDictsByDictTypeId: queryDictsByDictTypeId,
    getAuthToken: getAuthToken,
    uploadConfig: {
      uploadFileApiPath: UPLOAD_FILE_API_PATH,
      queryUploadFile: queryUploadFile,
      queryAliyunOssUploadPresigned: queryAliyunOssUploadPresigned,
      queryCtyunOssUploadPresigned: queryCtyunOssUploadPresigned,
    },
    fetchUserInfo,
    fetchBackendEnums,
    fetchLoggedInfo,
    ...appInitialStateImpl,
    backendDict: {
      queryDictsByDictTypeId,
      queryDictTypes,
    },
    backendEnum,
    ...loggedInfo,
  };
}


/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */

export const request: () => RequestConfig = () => {
  return {
    /**
     * Umi@4 请求基于 axios，默认是带括号 [] 的形式序列化
     * 例: a: [1,2,3]  默认序列化形式 a[]=1&a[]=2&a[]=3
     * 这里将其变更为 a=1&a=2&a=3 的形式
     */
    paramsSerializer: (params) => {
      return queryString.stringify(params);
    },
    baseURL: REQUEST_BASE_URL,
    ...errorConfig,
  };
};


export function rootContainer(container: React.ReactNode) {
  dayjs.locale('zh-cn');
  return container;
}
